package com.zmx.patientend.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.MakeAppointmentAdapter;
import com.zmx.patientend.adapter.RegistrationAdapter;
import com.zmx.patientend.adapter.RegistrationDateAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.DepartmentCategory;
import com.zmx.patientend.pojo.Registration;
import com.zmx.patientend.pojo.RegistrationDate;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.CustomToast;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
*时间：2020/5/12 12:37
*功能：挂号列表
*/
public class RegistrationListActivity extends BaseActivity implements RegistrationDateAdapter.OptiondateListener {

    private RelativeLayout relayout;

    private RegistrationDateAdapter adapter;
    private List<RegistrationDate> list;
    private RecyclerView recyclerView;

    private DepartmentCategory dc;

    private String date = format.format(new Date());

    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private RegistrationAdapter registrationAdapter;
    private List<Registration> registrations;

    private View mEmptyLayout;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_registration_list;
    }

    @Override
    protected void initViews() {

        dc = (DepartmentCategory) this.getIntent().getSerializableExtra("dc");
        setToolbar(R.id.tool_bar);
        recyclerView = findViewById(R.id.recycler_view);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);//设置为横向排列
        recyclerView.setLayoutManager(layout);

        //获取7天内的数据
        list = new ArrayList<>();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat sdfs = new SimpleDateFormat("MM-dd");
        List<Date> dateList = null;
        try {

            dateList = AllUtil.getBetweenDates(sdf.parse(sdf.format(new Date())), sdf.parse(AllUtil.getPastDate(-7)));
            for (Date date : dateList) {

                RegistrationDate rd = new RegistrationDate();
                rd.setDay(sdfs.format(date));
                rd.setToWeek(AllUtil.dateToWeek(sdf.format(date)));
                list.add(rd);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        adapter = new RegistrationDateAdapter(list,this);
        recyclerView.setAdapter(adapter);
        adapter.setOptiondateListener(this);
        adapter.setGetListener(position -> {
//                把点击的下标回传给适配器 确定下标

            adapter.setmPosition(position);
            adapter.notifyDataSetChanged();
        });

        mEmptyLayout = findViewById(R.id.empty);
        reView = findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        registrationAdapter = new RegistrationAdapter(mActivity);
        reView.setAdapter(registrationAdapter);
        registrations = new ArrayList<>();
        registrationAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Bundle bundle = new Bundle();
                bundle.putString("endtime",date);
                bundle.putSerializable("registration",registrations.get(listPosition));
                startActivity(RegistrationDoctorDetailsActivity.class,bundle);

            }
        });

        // 开启自动加载功能
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getHospVisit();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            refreshLayout.finishLoadMore(true);
            CustomToast.getInstance().showToastCustom(mActivity, "没有更多数据啦!", Gravity.BOTTOM);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:
                    Log.e("fdsaf","是否打发十分"+msg.obj.toString());
                    registrations.clear();
                    try {

                        JSONArray array = new JSONArray(msg.obj.toString());
                        Gson gson = new Gson();
                        for (int i =0 ;i<array.length();i++){

                            Registration registration = gson.fromJson(array.getJSONObject(i).toString(),Registration.class);
                            registrations.add(registration);

                        }
                        registrationAdapter.setListAndNotifyDataSetChanged(registrations);//就是设置list然后刷新
                        refreshLayout.finishRefresh(true);
                        if(registrations.size()>0){
                            mEmptyLayout.setVisibility(View.GONE);
                        }else{
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    public void getHospVisit() {

        List<String> l = new ArrayList<>();
        l.add(dc.getClass_id()+"");
        l.add(dc.getHosp_id()+"");
        l.add(date);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getHospVisit");
        params.put("data[showtime]", date);
        params.put("data[hosp_id]", dc.getHosp_id());
        params.put("data[class_id]", dc.getClass_id());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }

    @Override
    public void setOptiondateListener(String day) {

        Calendar c = Calendar.getInstance();
        String year = String.valueOf(c.get(Calendar.YEAR));

        date = year+"-"+day;
        Log.e("时间","时间紧急"+date);
        getHospVisit();

    }

}
